package es.cazadoresmadridejos.beans.manager.payment.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import es.cazadoresmadridejos.beans.dao.payment.PaymentDao;
import es.cazadoresmadridejos.beans.manager.payment.PaymentManager;
import es.cazadoresmadridejos.common.bean.dao.Dao;
import es.cazadoresmadridejos.common.bean.manager.impl.ManagerImpl;
import es.cazadoresmadridejos.model.Partner;
import es.cazadoresmadridejos.model.Payment;
import es.cazadoresmadridejos.model.Reason;

@Service
public class PaymentManagerImpl extends ManagerImpl<Payment> 
	implements PaymentManager{

	@Autowired 
	public void setDao(@Qualifier("paymentDao")
	Dao<Payment> dao) {
		this.dao = dao;
	}

	@Override
	public List<Payment> findAllByReason(Long idReason) {
		return ((PaymentDao)dao).findAllByReason(idReason);
	}

	@Override
	public List<Payment> findAllNotIncludedByReason(Long idReason) {
		List<Payment> payments = new ArrayList<Payment>();
		List<Partner> partners =  ((PaymentDao)dao).findAllNotIncludedByReason(idReason);
		
		for (Partner partner : partners) {
			Payment payment = new Payment();
			payment.setPartner(partner);
			payment.setPayment(BigDecimal.ZERO);
			payment.setReason(new Reason());
			payment.getReason().setId(idReason);
			payment.setType(partner.getHunterType());
			payments.add(payment);
		}
		
		Collections.sort(payments, new PaymentComparator());
		
		return payments;
	}
	
	class PaymentComparator implements Comparator<Payment>{

		@Override
		public int compare(Payment o1, Payment o2) {
			if(o1.getType().name().compareTo(o2.getType().name()) == 0){
				return o1.getPartner().getLastName().compareTo(o2.getPartner().getLastName());
			}
			return o1.getType().name().compareTo(o2.getType().name());
		}
		
	}

	@Override
	public void saveAll(List<Payment> payments) {
		for (Payment payment : payments) {
			super.save(payment);
		}
	}
}